package com.blog.security.util;



import com.blog.common.Constant;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName JwtUtil
 * @Destription jwt token 的处理，生成和验证
 * @Author 天堂小野花
 * @Date 2025/8/10  18:26
 * @Version 1.0
 */
public final class JwtSecurityUtil {
    private static Key getKeyInstance(String salt){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String apiKey = DatatypeConverter.printBase64Binary(salt.getBytes());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return secretKeySpec;
    }

    /**
     *  生成token
     * @param claims
     * @param salt
     * @param exp
     * @return
     */
    public static String createJavaWebTokenJwtAuth(Map<String,Object> claims, String salt, Integer exp){
        String token = Jwts.builder().setClaims(claims).setExpiration(DateUtils.addSeconds(new Date(), exp))
                .signWith(SignatureAlgorithm.HS256, getKeyInstance(salt)).compact();
        return token;
    }

    /**
     * 获取 jwt的载荷内容body
     * @param token
     * @param salt
     * @return
     */
    public static Map<String, Object> verifyJavaWebToken(String token, String salt){
        if(token.startsWith("\"")){
            token = token.replaceAll("^\"|\"$", "");
        }
        Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance(salt)).parseClaimsJws(token).getBody();
        return jwtClaims;
    }
    public static Authentication getAuthentication(String token, String salt){
        if(token.startsWith("\"")){
            token = token.replaceAll("^\"|\"$", "");
        }
        Map<String, Object> stringObjectMap = verifyJavaWebToken(token,salt);
        if(stringObjectMap == null || stringObjectMap.get(Constant.TOKEN_USER_INFO)==null){
            return null;
        }
        LinkedHashMap<String, Object> userDetails = (LinkedHashMap) stringObjectMap.get(Constant.TOKEN_USER_INFO);
        List<GrantedAuthority> authorities = userDetails == null ? AuthorityUtils.NO_AUTHORITIES : AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(userDetails.get("role")));
//        User principal = new User((String) userDetails.get(Constant.TOKEN_USER_INFO_USERNAME), "", authorities);
        return new UsernamePasswordAuthenticationToken(userDetails,token,authorities);
    }
}
